package com.faithlibraryplus;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jiaf
 */
public class Codecs{
    public static String decode(String hex){
        String utf8 = "";
        try {
            return new String(toByteArray(hex), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(
                    Codecs.class.getName()).log(Level.SEVERE, null, ex);
        }
        return utf8;
    }
    
    public static String encode(String s){
        String hex = "";
        try {
           hex = toHex(s.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(
                    Codecs.class.getName()).log(Level.SEVERE, null, ex);
        }
        return hex;
    }
    
    private static byte[] toByteArray(String hex) {
        int len = hex.length();
        if (len % 2 != 0){
            len++;
            hex += "0";
        }
        byte[] value= new byte[len/2];  
        for (int i = 0; i < len; i += 2){  
            value[i/2] = (byte)((
                    Character.digit(hex.charAt(i), 16) << 4) + 
                    Character.digit(hex.charAt(i + 1), 16)
                    );  
        }  
        return value;  
    }
    
    private static String toHex(byte[] b){
        String result = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            result = result+hex.toUpperCase();
        }
        return result;
    }
}
